package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"yim_server/yim_file/file_models"

	"yim_server/yim_file/file_rpc/internal/svc"
	"yim_server/yim_file/file_rpc/types/file_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileIsExistLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFileIsExistLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileIsExistLogic {
	return &FileIsExistLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// FileIsExist 文件是否存在
func (l *FileIsExistLogic) FileIsExist(in *file_rpc.FileIsExistRequest) (*file_rpc.FileIsExistResponse, error) {
	var file file_models.FileModels

	err := l.svcCtx.DB.Where("file_hash = ? AND user_id = ?", in.Hash, in.UserId).First(&file).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			logx.Error("未找到记录")
			return &file_rpc.FileIsExistResponse{IsExist: false}, nil
		}
		logx.Error(err)
		return nil, errors.New("error not nil")
	}

	return &file_rpc.FileIsExistResponse{IsExist: file.ID > 0, Url: file.FileUrl}, nil
}
